package com.example.springboot.controller;

import com.example.springboot.pojo.Admin;
import com.example.springboot.pojo.Result;
import com.example.springboot.service.AdminService;
import com.example.springboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.util.Encrypt;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/findById")
    public Admin findById(Integer userId){
        return adminService.findById(userId);
    }

//    @GetMapping("/adminInfo")
//    public Result<?> adminInfo(@RequestHeader(name = "Authorization") String token){
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        return Result.success(map);
//    }

    @PutMapping("/login")
    public Result<?> loginWorker(Integer userId, String password){
        Admin a = findById(userId);
        if(a != null){
            String str = Encrypt.toMD5(password);
            if(a.getPassword().equals(str)){
                // 登录成功
                Map<String,Object> claims = new HashMap<>();
                claims.put("userId",userId);
                claims.put("name",a.getName());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }else{
                return Result.error("密码错误");
            }
        }else{
            return Result.error("不存在的账号");
        }
    }
}
